<?php
include ("../main/inc/global.inc.php");

require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
require_once (api_get_path(CONFIGURATION_PATH).'profile.conf.php');

api_block_anonymous_users(); // only users who are logged in can proceed

$this_section='ads';

// Top part of the HTML
Display :: display_header('Advertisement');
?>

<script>
    $(document).ready(function() {
        var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
        var regex = new RegExp(expression);
        var preview_button = '<input type="button" id="preview" name="preview" value="Preview"></input>';
        $("#url").after(preview_button);
        $("#preview").prop("disabled", true);
        $("#url").bind("change paste keyup", function() {
            var value = $(this).val();
            if (value.match(regex)) {
                $("#preview").prop("disabled", false);
            } else {
                $("#preview").prop("disabled", true);
            }
        });
        $("#preview").click(function() {
            $.ajax({
                url: "preview.php",
                data: {
                    url: $("#url").val(),
                },
                type: "POST"
            }).done(function(msg) {
                $("#preview_div").html(msg);
                $("#preview_div").css("border", "2px solid #4271b5");
                $("#preview_div").css("background-color", "ghostwhite");
            }).fail(function() {
                alert("faile");
            });
        });
    });
</script>

<?php
global $_user;
// Input form for the advertisement registration
$form = new FormValidator('ads_reg');
//	NAME
$form->addElement('text', 'name', 'Name',  array('size' => 40));
$form->addRule('name',  get_lang('ThisFieldIsRequired'), 'required');
//	EMAIL
$form->addElement('text', 'email', get_lang('Email'), array('size' => 40));
$form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('email', get_lang('EmailWrong'), 'email');
//  ADDRESS
$form->addElement('text', 'address', 'Address', array('size' => 40));
$form->addElement('text', 'contact', 'Contact Number',   array('size' => 40));
$form->addRule('contact', get_lang('ThisFieldIsRequired'), 'required');
$form->addElement('text', 'keywords', 'Keywords', array('size' => 40));
//  BUDGET
$form->addElement('radio', 'budget', 'Budget', 'SGD 100.00', 100);
$form->addElement('radio', 'budget', NULL, 'SGD 50.00', 50);
$form->addElement('radio', 'budget', NULL, 'SGD 30.00', 30);
//  URL
$form->addElement('text', 'url', 'URL link', array('size' => 80, 'id' => 'url'));
$form->addRule('url', get_lang('ThisFieldIsRequired'), 'required');
//	reCAPTCHA
require_once (api_get_path(LIBRARY_PATH).'formvalidator/Rule/ReCaptcha.php');
$form->addElement('recaptcha', 'recaptcha_response_field', 'reCAPTCHA', array('size' => 40));
$reCaptcha = new ReCaptcha_Rule();
$form->registerRule('check_recaptcha', null, $reCaptcha);
$form->addRule('recaptcha_response_field', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('recaptcha_response_field', 'Enter correct captha text', 'check_recaptcha', $form);
$form->addElement('submit', 'submit', get_lang('Ok'));
$form->addElement('hidden', 'user_id', $_user['user_id']);
$defaults['budget'] = 100;
$defaults['name'] = $_user['firstName'].' '.$_user['lastName'];
$defaults['email'] = $_user['mail'];
$form->setDefaults($defaults);

if ($form->validate()) {
    // Validate the result and store the ads information into the database
    $values = $form->exportValues();
    $is_img = substr($values['url'], -strlen('.img')) == '.img';
    $keywords = explode(" ", $values['keywords']);
    $ads_id = Database::add_ads($values['name'], $values['address'],
            $values['email'], $values['contact'], $values['budget'],
            $values['url'], $is_img, $values['user_id'], $keywords);
    echo '<p>The Advertisement has been added.</p>';
    echo '<p>Your Advertisement can be viewed on the site</p>';
    echo '<p>Each view will be charged for SGD 0.01</p>';
} else {
    // Display user's ads and the ads application form 
    $user_ads = Database::get_ads_by_user_id($_user['user_id']);
    if (count($user_ads)) {
        echo '<h1>My Existing Ads</h1>';
        echo '<table>';
        echo '<tr><th>Ads ID</th><th>URL</th></tr>';
        foreach ($user_ads as $u) {
            echo '<tr><td>'.$u['ads_id'].'</td><td>'.htmlspecialchars($u['url']).'</td></tr>';
        }
        echo '</table>';
    }
    echo '<h1>Ads Registration</h1>';
    $form->display();
    echo '<div id="preview_div" style="width:800px; margin:0 auto; padding:20px;"></div>';
}
?>
<a href="<?php echo api_get_path(WEB_PATH); ?>">&lt;&lt; <?php echo get_lang('Back'); ?></a>
<?php

// Footer
Display :: display_footer();

?>
